package com.rm.wechatapp.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.rm.wechatapp.service.IWeixinService;
import org.springframework.stereotype.Service;

/**
 * 微信小程序Service业务层处理
 *
 * @author sh
 * @date 2023-03-27
 */
@Service
public class WeixinServiceImpl implements IWeixinService {

    /**
     * 根据微信小程序用户code获取openId
     *
     * @param code 用户code
     * @return openId
     */
    @Override
    public String getOpenId(String code){
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url
                .replace("{0}", "wx1ba3241e29885615")
                .replace("{1}", "528659639003ba112a1bfa72ac85fa93")
                .replace("{2}", code);
        String jsonString = HttpUtil.get(replaceUrl);
        JSONObject json = JSONUtil.parseObj(jsonString);
        return json.getStr("openid");
    }

}
